﻿
$(document).ready(function () {

    InitMenuItemsUI($('.sp-menu-collapse'));

    $('ol.menu-item-sortable').nestedSortable({
        disableNesting: 'no-nest',
        forcePlaceholderSize: true,
        handle: 'h4',
        //helper:	'clone',
        items: 'li.menu-item-sortable-item',
        //maxLevels: 3,
        opacity: .6,
        placeholder: 'ui-state-highlight',
        revert: 250,
        tabSize: 25,
        tolerance: 'pointer',
        toleranceElement: 'div.sp-menu-collapse',
        start: function (event, ui) {
            $(event.srcElement).parents('.sp-menu-collapse').accordion("option", "disabled", true);
        },
        stop: function (event, ui) {
            window.setTimeout(function () {
                $(event.srcElement).parents('.sp-menu-collapse').accordion('option', 'disabled', false);
            }, 100);
        },
        update: function (event, ui) {
            var menuItem = $(event.srcElement).parents('li.menu-item-sortable-item:first');
            var parentInput = $(menuItem).find('input[name$="menuitem-parent.RelatedContentIds"]:first');
            var sortOrderInput = $(menuItem).find('input[name$="SortOrder"]:first');
            var parent = $(menuItem).parents('li.menu-item-sortable-item:first');
            if (parent.length > 0)
                var parentId = $(parent).children('.sp-menu-collapse').find('input[name$="MenuItem.Editor.Id"]').val();
            else
                var parentId = $('#MenuId').val();
            $(parentInput).val(parentId);
            var sortOrders = GetUpdatedSortOrders();

            var postData = {
                parentId: parentId,
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
            };

            for (var i = 0; i < sortOrders.length; i++) {
                postData["updatedSortOrders[" + i + "].Key"] = sortOrders[i].Key;
                postData["updatedSortOrders[" + i + "].Value"] = sortOrders[i].Value;
            }

            var updateUrl = $(menuItem).find('.saveMenuItem:first').val().replace('MenuItemAdmin/Edit', 'MenuItemAdmin/UpdateParentAndSortOrder');
            ToggleMenuAjaxIndicator(menuItem, true);
            $.ajax({
                url: updateUrl,
                data: postData,
                type: 'POST',
                context: menuItem,
                complete: function () {
                    ToggleMenuAjaxIndicator(this, false);
                }
            });
        }
    });

    $('.menu-item-sortable').disableSelection();

    $('.addMenuItem').click(function () {
        $(this).siblings('.ajax-indicator').css('visibility', 'visible');
        $(this).attr('disabled', 'disabled').addClass('ui-state-disabled');
        $(this).siblings('.edit-form').addClass('ui-state-disabled');
        var data = $(this).siblings('.edit-form').find('input').add($('input[name="__RequestVerificationToken"]')).serialize();
        $.ajax({
            url: $(this).val(),
            data: data,
            type: 'POST',
            context: this,
            success: function (result) {
                $(this).siblings('.edit-form').html(result);
            },
            complete: function () {
                $('#menu-instructions').hide();
                $(this).siblings('.ajax-indicator').css('visibility', 'hidden');
                $(this).removeAttr('disabled').removeClass('ui-state-disabled');
                $(this).siblings('.edit-form').removeClass('ui-state-disabled');
                if ($(this).siblings('.edit-form').find('.ajax-result').children().length > 0) {
                    var newEditor = $('.ajax-result').children();
                    newEditor.appendTo($('#sp-menu-item-list-inner .menu-item-sortable'));
                    $('.ajax-result').remove();
                    InitMenuItemsUI($(newEditor).children('.sp-menu-collapse'));
                }
            }
        });
        return false;
    });

    $('.addContentItemMenuItems').click(function () {
        var selectedContent = $(this).siblings('.edit-form').find('.ui-tabs-panel:not(.ui-tabs-hide) input:checked');
        if (selectedContent.length > 0) {
            $(this).siblings('.ajax-indicator').css('visibility', 'visible');
            $(this).attr('disabled', 'disabled').addClass('ui-state-disabled');
            $(this).siblings('.edit-form').addClass('ui-state-disabled');
            var data = {
                "__RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
            };
            $(selectedContent).each(function (index) {
                data["contentItemIds[" + index + "]"] = $(this).val();
            });
            $.ajax({
                url: $(this).val(),
                data: data,
                type: 'POST',
                context: this,
                success: function (result) {
                    $('#menu-instructions').hide();
                    $(this).siblings('.edit-form').find('.ui-tabs-panel input:checked').removeAttr('checked');
                    if ($(result).children('.menu-item-sortable-item').length > 0) {
                        var newEditor = $(result).children('.menu-item-sortable-item');
                        newEditor.appendTo($('#sp-menu-item-list-inner .menu-item-sortable'));
                        InitMenuItemsUI($(newEditor).children('.sp-menu-collapse'));
                    }
                },
                complete: function () {
                    $(this).siblings('.ajax-indicator').css('visibility', 'hidden');
                    $(this).removeAttr('disabled').removeClass('ui-state-disabled');
                    $(this).siblings('.edit-form').removeClass('ui-state-disabled');
                }
            });
            return false;
        }
    });

    $('.saveMenuItem').live('click', function () {
        $(this).siblings('.ajax-indicator').css('visibility', 'visible');
        ToggleMenuAjaxIndicator($(this).parents('.menu-item-sortable-item:first'), true);
        var data = $(this).siblings('.edit-form').find('input').add($('input[name="__RequestVerificationToken"]')).serialize();        
        $.ajax({
            url: $(this).val(),
            data: data,
            cache: false,
            type: 'POST',
            context: this,
            success: function (result) {
                $(this).siblings('.edit-form').html(result);
            },
            complete: function () {
                ToggleMenuAjaxIndicator($(this).parents('.menu-item-sortable-item:first'), false);
            }
        });
        return false;
    });

    $('.delete-menu-item').live('click', function () {
        var hasChildren = $(this).parents('li.menu-item-sortable-item:first').find('li.menu-item-sortable-item').length > 0;
        if (hasChildren) {
            alert('Cannot remove a menu item with children.  Please move or remove children before removing this item.');
        } else {
            $(this).siblings('.ajax-indicator').html('Deleting...').css('visibility', 'visible');
            ToggleMenuAjaxIndicator($(this).parents('.menu-item-sortable-item:first'), true);
            var data = {
                "__RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
            };

            $.ajax({
                url: $(this).attr('href'),
                data: data,
                type: 'POST',
                context: this,
                success: function (result) {
                    $(this).parents('.menu-item-sortable-item:first').fadeOut('slow', function () {
                        $(this).remove();
                        if ($('.menu-item-sortable-item').length == 0) {
                            $('#menu-instructions').show();
                        }
                    });
                }
            });
        }
        return false;
    });

    function SearchContent() {
        var q = $('#contentSearchQuery').val();
        if (q != '' && $('#contentSearchQuery').attr('disabled') != 'disabled') {
            $('#contentSearchQuery').val('Searching...').attr('disabled', 'disabled').addClass('ui-state-disabled');
            var tabs = $('#content-item-tab-filters');
            var types = $.map($(tabs).parents('.menuitem-content-item-selector').find('.ui-multiselect-menu').find('input:checked'), function (checkbox, index) {
                return "types[" + index + "]=" + checkbox.value;
            }).join("&");

            var url = $('#content-item-search-tab').data('href.tabs');
            if (url.indexOf("?") >= 0)
                url = url.substring(0, url.indexOf("?"));
            url += "?" + types;
            url += '&q=' + q;

            var tabIndex = $(this).parents('.ui-tabs-panel:first').index('.ui-tabs-panel');
            $(tabs).tabs("url", tabIndex, url);
            if (!$(this).is('.ui-tabs-hide'))
                $(tabs).tabs('load', tabIndex);
        }
        return false;
    }

    $('.menuitem-content-item-selector .pager a').live('click', function () {
        var tabs = $('#content-item-tab-filters');
        var url = $(this).attr('href');
        var index = $(this).parents('.ui-tabs-panel:first').index('.ui-tabs-panel');
        $(tabs).tabs("url", index, url);
        $(tabs).tabs('load', index);
        return false;
    });

    function GetUpdatedSortOrders() {
        var changedItems = [];
        $('li.menu-item-sortable-item').each(function () {
            var sortOrderEditor = $(this).find('input[name$="SortOrder"]:first');
            var oldSortOrder = $(sortOrderEditor).val();
            var newSortOrder = $(this).prevAll('li').length;
            if (oldSortOrder != newSortOrder) {
                $(sortOrderEditor).val(newSortOrder);
                var id = $(this).find('input[name$="Editor.Id"]:first').val();
                changedItems.push({
                    "Key": id,
                    "Value": newSortOrder
                });
            }
        });
        return changedItems;
    }

    function ToggleMenuAjaxIndicator(menuItem, show) {
        if (show) {
            if ($(menuItem).find('.ui-accordion-header:first').is('.ui-state-active')) { //expanded
                $(menuItem).find('.ui-accordion-content:first').find('.ajax-indicator').css('visibility', 'visible');
            } else { //collapsed
                $(menuItem).find('h4.ui-accordion-header:first').append('<span class="ajax-indicator" style="visibility:visible; position: absolute; right:-100px; top:5px;">Saving...</span>');
            }

            $(menuItem).find('.saveMenuItem:first').attr('disabled', 'disabled').addClass('ui-state-disabled');
            $(menuItem).find('.edit-form:first').addClass('ui-state-disabled');
        } else {
            $(menuItem).find('.ui-accordion-content:first').find('.ajax-indicator').css('visibility', 'hidden');
            $(menuItem).find('.ui-accordion-header:first').find('.ajax-indicator').remove();
            $(menuItem).find('.saveMenuItem:first').removeAttr('disabled').removeClass('ui-state-disabled');
            $(menuItem).find('.edit-form:first').removeClass('ui-state-disabled');
        }
    }


    function InitMenuItemsUI(items) {
        $(items).each(function () {
            $(this).find('.contentTypeSelector').multiselect({
                noneSelectedText: 'Select content types',
                selectedList: 99,
                header: false,
                click: function (event, ui) {
                    if (ui.value == '*') {
                        if (ui.checked) {
                            $(event.srcElement).parents('li').siblings('li').find('input').removeAttr('checked');
                        }
                    } else {
                        $(event.srcElement).parents('li').siblings('li').find('input[value="*"]').removeAttr('checked');
                    }

                },
                close: function () {
                    $('#content-item-tab-filters .ui-tabs-panel').html('');
                    GetContentByType();
                }
            });

            if ($(this).find('.menu-item-advanced input[value!=""]').length == 0) {                
                $(this).find(".menu-item-advanced h3")
                    .expandoControl(function (controller) { return controller.nextAll(".details"); }, { collapse: true, remember: false })
                    .css('cursor', 'pointer')
                    .click(function () {
                        $(this).find('.expando-glyph').trigger('click');
                    });
            }

            $(this).accordion({
                collapsible: true,
                autoHeight: false,
                active: $(this).parents('#sp-menu-item-list').length > 0 ? false : 0
            });
        });
    }

    $('input').live('keypress', function (e) {
        if (e.which == 13) { //Enter keycode
            if ($(this).is('#contentSearchQuery')) {
                SearchContent();
            }
            else {
                var menuParent = $(this).parents('.sp-menu-collapse');
                if ($(menuParent).length > 0) {
                    $(menuParent).find('.ui-accordion-content>button.secondaryAction').click();
                } else {
                    $('button[name="submit.Save"]').click();
                }
            }
            e.preventDefault();
        }
    });
});

function GetContentByType() {
    var tabs = $('#content-item-tab-filters');
    var headers = $(tabs).find(".content-item-tab-header");
    var types = $.map($(tabs).parents('.menuitem-content-item-selector').find('.ui-multiselect-menu').find('input:checked'), function (checkbox, index) {
        return "types[" + index + "]=" + checkbox.value;
    }).join("&");
    $(tabs).children('.ui-tabs-panel').each(function (index) {
        var url = $(headers[index]).data('href.tabs');
        if (url.indexOf("?") >= 0)
            url = url.substring(0, url.indexOf("?"));
        url += "?" + types;
        $(tabs).tabs("url", index, url);
        if (!$(this).is('.ui-tabs-hide'))
            $(tabs).tabs('load', index);
    });
}